use crate::cliopts::OutputFormat;
use csv::Reader;
use serde::{Deserialize, Serialize};
use std::fs;

#[derive(Deserialize, Debug, Serialize)]
#[serde(rename_all = "PascalCase")]
struct Player {
    name: String,
    position: String,
    #[serde(rename = "DOB")]
    dob: String,
    nationality: String,
    #[serde(rename = "Kit Number")]
    kit: u8,
}

pub fn process_csv(input: &str, output: String, format: OutputFormat) -> anyhow::Result<()> {
    let mut reader = Reader::from_path(input)?;
    let mut ans = Vec::with_capacity(128);
    let header = reader.headers()?.clone();
    for result in reader.records() {
        let record = result?;
        // header.iter() -> 使用header的迭代器
        // record.iter() -> 使用record的迭代器
        // zip() -> 将两个迭代器合并为一个元组的迭代器[(header, record), ...]
        // collect::<Value>() -> 将元组的迭代器转换为JSON Value
        // let json_ans = header.iter().zip(record.iter()).collect::<Value>();
        let mut json_object = serde_json::Map::new();
        for (item, value) in header.iter().zip(record.iter()) {
            json_object.insert(item.to_string(), value.into());
        }
        ans.push(serde_json::Value::Object(json_object));
    }
    let content = match format {
        OutputFormat::Json => serde_json::to_string_pretty(&ans)?,
        OutputFormat::Yaml => serde_yaml::to_string(&ans)?,
        OutputFormat::Toml => {
            let toml_val = toml::Value::try_from(serde_json::Value::Array(ans))?;
            toml::to_string_pretty(&toml_val)?
        }
    };

    fs::write(output, content)?;

    Ok(())
}
